package com.five.common.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.UUID;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.five.common.constant.DefaultAvatarUrl;
import com.five.common.constant.DefaultPassword;
import com.five.common.entity.LoginTable;
import com.five.common.entity.ModPasswordDTO;
import com.five.common.entity.StudentLoginer;
import com.five.common.result.Result;
import com.five.common.service.LoginTableService;
import com.five.common.utils.Md5Util;
import com.five.common.utils.MinioUtils;
import com.five.common.utils.RedisUtil;
import com.five.common.utils.SendSmsUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.concurrent.ThreadLocalRandom;



        import cn.hutool.captcha.CaptchaUtil;
        import cn.hutool.captcha.LineCaptcha;
        import cn.hutool.captcha.generator.RandomGenerator;
        import cn.hutool.extra.pinyin.PinyinUtil;
        import com.five.common.constant.DefaultAvatarUrl;
        import com.five.common.constant.DefaultPassword;
        import com.five.common.entity.LoginTable;
        import com.five.common.entity.ModPasswordDTO;
        import com.five.common.entity.StudentLoginer;
        import com.five.common.result.Result;
        import com.five.common.service.LoginTableService;
        import com.five.common.utils.Md5Util;
        import com.five.common.utils.MinioUtils;
        import com.five.common.utils.RedisUtil;
        import com.five.common.utils.SendSmsUtils;
        import io.swagger.v3.oas.annotations.Operation;
        import io.swagger.v3.oas.annotations.tags.Tag;
        import jakarta.servlet.http.HttpSession;
        import lombok.extern.slf4j.Slf4j;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;
        import org.springframework.web.multipart.MultipartFile;

        import java.util.Base64;
        import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ywt
 * @since 2024-07-18
 */
@Tag(name = "公共登录接口")
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/loginTable")
public class LoginTableController {
    @Autowired
    private LoginTableService loginTableService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private SendSmsUtils sendSmsUtils;

    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result login(String phone, String password, String verifyCode, HttpSession session) {
        Object o = redisUtil.get("verifyCode");
        if (o == null) {
            return Result.error("验证码已过期!");
        }
        if (!verifyCode.equals(o)) {
            return Result.error("验证码错误!");
        }
        String md5String = Md5Util.getMD5String(password);
        LoginTable login = loginTableService.login(phone, md5String, verifyCode);
        if (login == null) {
            return Result.error("用户名或密码错误!");
        }
        //将数据存储到session对象中
        session.setAttribute("name", login.getName());
        // 生成token将用户信息存到redis中
        String token = UUID.randomUUID().toString(true).replace("-","");
        login.setToken(token);
        // token为键 name为值设置时长为3小时
        redisTemplate.opsForValue().set(token,login.getName(),3, TimeUnit.HOURS);
        log.info("用户登录成功，用户名：{}", login.getName());
        return Result.ok(login);
    }

    //生成图形验证码
    @GetMapping("/getVerifyCode")
    @Operation(summary = "生成图形验证码")
    public String getVerifyCode() {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        lineCaptcha.setGenerator(randomGenerator);
        //生成code
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();
        log.info(code);
        redisUtil.set("verifyCode", code);
        return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(lineCaptcha.getImageBytes());
    }

    //添加登录者(学生)
    @Operation(summary = "添加登录者")
    @PostMapping("/addStudentLoginer")
    public Result addStudentLoginer(String sNumber, String phone, String sName) {
        StudentLoginer studentLoginer = new StudentLoginer();
        studentLoginer.setSNumber(sNumber);
        studentLoginer.setPhone(phone);
        studentLoginer.setName(PinyinUtil.getFirstLetter(sName, ""));
        studentLoginer.setPassword(DefaultPassword.DEFAULTPASSWORD);
        studentLoginer.setAvatar(DefaultAvatarUrl.DEFAULTAVATARURL);
        studentLoginer.setType(0);
        Integer i = loginTableService.addStudentLoginer(studentLoginer);
        return i > 0 ? Result.ok(studentLoginer) : Result.error("操作异常");
    }

    //查看登录者的信息
    @Operation(summary = "查看登录者的信息")
    @GetMapping("/getLoginInfo")
    public Result getLoginInfo(String phone) {
        LoginTable loginTable = loginTableService.getLoginInfo(phone);
        return loginTable != null ? Result.ok(loginTable) : Result.error("数据错误");
    }

    //修改用户头像
    @Operation(summary = "修改用户头像和")
    @PutMapping("/modAvatar")
    public Result modAvatarOrPhone(String avatar, Integer id) {
        int end = loginTableService.modAvatarOrPhone(avatar, id);
        if (end > 0) {
            return Result.ok("修改成功");
        }
        return Result.error("系统错误");
    }

    //上传头像
    @Operation(summary = "上传头像")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String url = minioUtils.upload(file);
        log.error(url);
        return Result.ok(url);
    }

    //修改密码
    @Operation(summary = "修改密码")
    @PutMapping("/modPassword")
    public Result modPassword(@RequestBody ModPasswordDTO modPasswordDTO) {
        String o = (String) redisUtil.get("phoneCode");
        if (o == null) {
            return Result.error("验证码已过期");
        }
        if (!modPasswordDTO.getCode().equals(o)) {
            return Result.error("验证码输入有误");
        }
        modPasswordDTO.setNewPassword(Md5Util.getMD5String(modPasswordDTO.getNewPassword()));
        int end = loginTableService.modPassword(modPasswordDTO);
        return end > 0 ? Result.ok() : Result.error("系统出错");
    }

    //获取手机验证码
    @Operation(summary = "获取手机验证码")
    @GetMapping("/getPhoneCode")
    public Result getPhoneCode(String phone) {
        String phoneCode = String.
                valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));
        log.info(phoneCode);
        try {
            sendSmsUtils.send(phoneCode, phone);
        } catch (Exception e) {
            e.printStackTrace();
        }

        redisUtil.set("phoneCode", phoneCode);
        return Result.ok();
    }

    /**
     * 获取用户名
     * @param
     * @return
     */
    @GetMapping("/getUsername")
    public Result getUsername(@RequestHeader("Token") String token) {
        // 通过前端请求携带过来的token去获取Redis中用户信息
        String name = redisTemplate.opsForValue().get(token);
//        String name = (String) session.getAttribute("name");
        System.out.println("name = " + name);
        if (name == null) {
            return Result.error("未登录或会话过期");
        }
        return Result.ok(name);
    }
}

